-- Author: shunguo.chen
-- Date: 2016-06-17 11:42:45
--
-- RewardController
--

local RewardView = import("..views.RewardView")
local RewardMonitorView = import("..views.RewardMonitorView")
local RewardGetBoxRewardView = import("..views.RewardGetBoxRewardView")
local BoxItemVo = import("..models.BoxItemVo")
local RewardRecommendView = import("..views.RewardRecommendView")
local PayNoticeView = import("..views.PayNoticeView")
local LotteryDropView = require("app.mall.views.LotteryDropView")
local QuickLevelView = import("..views.QuickLevelView")
local RewardHeroTreasureBuyView = import("..views.RewardHeroTreasureBuyView")
local RewardHeroTreasureBuyExpView = import("..views.RewardHeroTreasureBuyExpView")
local RewardHeroTrearsureTipsPanel = import("..views.RewardHeroTrearsureTipsPanel")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
	self.super.ctor(self, params)

end

function ClassRef:init()
	self._model = app:getInst("RewardModel")

	self._curId = 1

	self._playerHandler = UD.player:onChanged(handler(self, self.updatePlayer))
	self._itemChangeHandler = UD:onChanged("bag", handler(self, self.updateItem))
end

function ClassRef:removeListeners()
	self.super.removeListeners(self)
	UD.player:unChanged(self._playerHandler)
	UD:unChanged("bag", self._itemChangeHandler)
end

function ClassRef:listEvent()
	return {
		"onDailyUpdate",
	}
end

function ClassRef:onEvent(eventName, data)
	--if eventName == "onPaySuccess" then
	if eventName == "onDailyUpdate" then
		self:onSwitchPanel(self._curId,self._curType,self._curSubType)
	end
end

function ClassRef:openView(data)
	if cc.isDead(self._view) then
		self._view = RewardView.new(app.mvc.VIEWTYPE_BLUR, self._model:getAllActivitys())
		self._view:onCloseView(handler(self, self.closeView))
		self._view:onClearView(handler(self, self.clearView))
		self._view:onOperate(handler(self, self.onOperate))
		self._view:onSwitchPanel(handler(self, self.onSwitchPanel))
	end
	self:addChild(self._view)
	self._view:refreshRedPoint(self._model:getAllActivityRedPoints())
	--data有值的时候 必然是trace的值 没有值的时候为nil显示
	if data then
		self._view:show(data)
	end
end

--打開精彩活動界面
function ClassRef:openMonitorView(data)
	if cc.isDead(self._monitorView) then
		self._monitorView = RewardMonitorView.new(app.mvc.VIEWTYPE_BLUR)
		self._monitorView:onCloseView(handler(self, self.closeMonitorView))
		self._monitorView:onClearView(handler(self, self.clearMonitorView))
		self._monitorView:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._monitorView)
	--data有值的时候 必然是trace的值 没有值的时候为nil显示
	if data then
		self._monitorView:show(data)
	end

	self._model:reqMonitorActivityInfo()
end

function ClassRef:closeMonitorView(data)
	if self._monitorView then
		self:removeChild(self._monitorView, data)
	end
end

function ClassRef:clearMonitorView()
	if self._monitorView then
		self._monitorView = nil
	end
end


function ClassRef:refreshMonitorView(allActivityList)
	if not cc.isDead(self._monitorView) then
		self._monitorView:initLeftList(allActivityList)
	end
end


function ClassRef:refreshMonitorTaskPanel(data)
	if not cc.isDead(self._monitorView) then
		self._monitorView:refreshDataAfterGetTaskAward(data)
	end
end

-----------------------------------------

function ClassRef:openFatePanel(c)
	self._model._fateStoneModel._openChapter = c
	local acts = self._model:getAllActivitys()
	if acts and acts[Enums.ActivityType.Fate] then
		self:openView(acts[Enums.ActivityType.Fate])
	else
		-- tips
	end
end

function ClassRef:clearView()
	if self._view then
		self._view = nil
	end

	self._curId = nil

	self._model:clearCardRedPoint()
end
------------------------------------------------------------
function ClassRef:onOperate(operate, data)
	--print("RewardController:onRewardOperate operate = " .. operate)

	if operate == "getSignAward" then
		self._model:reqGetSignAward(data.uuid,data.idx)
	elseif operate == "getThreeDayAward" then
		self._model:reqGetThreeDayAward(data.uuid,data.idx)
    elseif operate == "selectWelfare" then
		self._curId = data.uuid
		self._curType = data.type
		self._curSubType = data.subType
        if self._curSubType == Enums.ActivitySubType.FirstRecharge then
			self._model:reqGetFirstRechargeInfos(data.uuid)
        elseif self._curSubType == Enums.ActivitySubType.Sign then
			self._model:reqGetMonthSignData(data.uuid)
        elseif self._curSubType == Enums.ActivitySubType.Give then
			self._model:reqGetTaskActivityData(data.uuid)
		elseif data.subType == Enums.ActivitySubType.FirstKill  then
			self._model:reqFistKillInfos(data.uuid)
		elseif self._curSubType == Enums.ActivitySubType.Fund then
			self._model:reqGetFundInfos(data.uuid)
		elseif self._curSubType == Enums.ActivitySubType.CDKey then
			self:refreshCurrentPanel(data)
		elseif self._curSubType == Enums.ActivitySubType.Through then
			self._model:reqLevelPromotionInfo(data)
		elseif self._curSubType == Enums.ActivitySubType.Privilege then
			self._model:reqSuperPrivilegeInfo(data)
		elseif self._curSubType == Enums.ActivitySubType.AmazingBox then
			self._model:reqGetAmazingAwardInfo(self._curId)
		elseif self._curSubType == Enums.ActivitySubType.SunfuryTreasure then
			self._model:reqGetAmazingAwardInfo(self._curId)
		elseif self._curSubType == Enums.ActivitySubType.HeroTreasure then
			--假设数据
			self._model:reqHeroTreasureActivityInfo(self._curId)
		end
	elseif operate == "getMonthSignAward" then
		self._model:reqGetMonthSignAward(data.uuid,data.idx)
	elseif operate == "changeTraceStatus" then
		self._model:reqChangeTrackStatus(data[1],data[2])
	elseif operate == "getTaskActivityAward" then
		self._model:reqGetTaskActivityAward(data[1],data[2])
	elseif operate == "getMonitorTaskActivityAward" then
		self._model:reqGetMonitorTaskActivityAward(data[1],data[2])
	elseif operate == "openMiraculousCard" then
		self._model:reqOpenMiraculousCard()
	elseif operate == "getMiraculousCardInfo" then
		self._model:reqGetCardInfos(data[1])
	elseif operate == "getFirstRechargeAward" then
		self._model:reqGetFirstChargeReward(data.uuid)
	elseif operate == "useCDKey" then
		self._model:reqGetGiftCode(data)
	elseif operate == "hideRecommendPanel" then
		if data == 6 then
			UD.localStorage:setRecommended(true)
			UD:updateLocalStorage(UD.localStorage)
		end
	elseif operate == "gotoAppShop" then
		UD.localStorage:setRecommended(true)
		UD:updateLocalStorage(UD.localStorage)
		if cc.isAlive(self._recommendView) then
			self._recommendView:refreshRecommendText()
		end
		app.channelAPI:jumpToAppShop()
	elseif operate == "openAmazingAward" then
		self._model:reqOpenAmazingAward(data)
	elseif operate == "buyLevelDirect" then
		--{activityData = self._data,idx = id}
		self._model:reqBuyLevelPromotion(data.activityData,data.idx)
	elseif operate == "showHeroTreasureDes" then
		self:showHeroTreasureBuyOrDes({type=1})
	elseif operate == "heroTreasureStartGetAward" then
		self._model:reqGetHeroTreasureReward(data.activityUID, data.lv, data.isGolden)
	elseif operate == "buyGoldenHeroTreasure" then
		self._model:reqBuyHeroTreasureGoldenReward(data)
	elseif operate == "openBuyHeroTreasureView" then
		--打开购买黄金奖励界面
		self:showHeroTreasureBuyOrDes(data)
	elseif operate == "gotoWeekWork" then
		--前往每日追求界面
		UIHandler:handleMessage({id = Constant.FUNC_DAILY_WORKFLOW, mode="open", data = 3})
	elseif operate == "openBuyHeroTreasureExpView" then
		--显示购买黄金经验界面
		self:showHeroTreasureBuyExpView(data)
	elseif operate == "showHeroTreasureTips" then
		self:showHeroTreasureTips(data.rewards,data.pos)
	elseif operate == "buyHeroTreasureExp" then
		self._model:reqBuyHeroTreasureExp(data.activityUID, data.buyNum)
	end
end

function ClassRef:onSwitchPanel(activityId,type,subType)
	self._curId = activityId
	self._curType = type
	self._curSubType = subType

	if type == Enums.ActivityType.Fate then

	elseif type == Enums.ActivityType.Into then
		if self._curSubType and self._curSubType > 0 then
			self._model:reqGetThreeDayData(self._curId)
		else
			self._model:reqGetSignData(self._curId)
		end
	elseif type == Enums.ActivityType.Carnival then

	elseif type == Enums.ActivityType.Welfare then
		if not cc.isDead( self._view ) then
        	self._view:initWelfareLeftList(self._model:getAllActivitys()[Enums.ActivityType.Welfare], activityId, self._model:getAllActivityRedPoints())
		end
	elseif type == Enums.ActivityType.Draw then
		self._model:reqGetCardInfos(self._curId)
	end

end

function ClassRef:refreshCurrentPanel(data)
	if self._curId == data.uuid and not cc.isDead( self._view ) then
		self._view:refreshCurrentPanel(data)
	end
	
	if self._curPayNoticeId == data.uuid and not cc.isDead(self._payNoticeView) then
		self._payNoticeView:refreshCurrentPanel(data)
	end
end

function ClassRef:refreshAllActivityRedPoints(data)
	if not cc.isDead( self._view ) then
		self._view:refreshRedPoint(data)
	end
end

--播放获得奖励特效
function ClassRef:playFirstRechargeGetAwards(rewards, sevenDayActivityId)
	if cc.isDead( self._getRewardView ) then
		local items = {0,0,0,0,0}
		for i,v in ipairs(rewards) do
			items[i] = BoxItemVo.new()
			items[i]:initWithBagItem(v)
		end
		self._getRewardView = RewardGetBoxRewardView.new(app.mvc.VIEWTYPE_BLUR,items)
		self._getRewardView:onCloseView(handler(self, self.closeGetAwardView))
	end
	self:addChild(self._getRewardView)
	self._getRewardView:stopAllActions()
	self._getRewardView:show()

	if not cc.isDead( self._view ) then
    	self._view:initWelfareLeftList(self._model:getAllActivitys()[Enums.ActivityType.Welfare], sevenDayActivityId, self._model:getAllActivityRedPoints())
	end
end

function ClassRef:closeGetAwardView()
	if not cc.isDead( self._getRewardView ) then
		self:removeChild(self._getRewardView)
		self._getRewardView = nil
	end
end

function ClassRef:isInFirstRechargeGetView()
	return self._getRewardView ~= nil
end

function ClassRef:refreshWelfareSelected(activityId)
	if not cc.isDead( self._view ) then
		self._view:initWelfareLeftList(self._model:getAllActivitys()[Enums.ActivityType.Welfare], activityId, self._model:getAllActivityRedPoints())
	end
	
	if cc.isDead(self._view) and not cc.isDead(self._payNoticeView) then
		self:closePayNoticeView()
		self:openView(self._model:getWelfareActivityByUid(activityId))
	end
end

-- 打开推荐界面
function ClassRef:openRecommendView(idx)
	if cc.isDead(self._recommendView) then
		self._recommendView = RewardRecommendView.new(app.mvc.VIEWTYPE_BLUR,idx)
		self._recommendView:onCloseView(handler(self, self.closeRecommendView))
		self._recommendView:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._recommendView)
	self._recommendView:stopAllActions()
	self._recommendView:setVisible(false)
	-- 延迟0.5秒再显示UI
	self._recommendView:performWithDelay(function()
		self._recommendView:show()
	end, 0.5)
end

-- 关闭推荐界面
function ClassRef:closeRecommendView()
	if not cc.isDead( self._recommendView ) then
		self:removeChild(self._recommendView)
		self._recommendView = nil
	end
end

------------------------------------------------------------
-- 打开付费弹窗界面
function ClassRef:openPayNoticeView(data)
	if cc.isDead(self._payNoticeView) then
		self._payNoticeView = PayNoticeView.new()
		self._payNoticeView:onCloseView(handler(self, self.closePayNoticeView))
		self._payNoticeView:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._payNoticeView)
	if data then
		local info = self._model:getWelfareActivityBySubType(data)
		if info then
			self._payNoticeView:show(info)

			self._curPayNoticeId = info.uuid
			local dailyTimes = UD:getValueFromGenericByKey("payNoticeDailyTimes"..info.subType) or 0
			UD:saveGeneric("payNoticeDailyTimes"..info.subType, tonumber(dailyTimes)+1)
			UD:saveGeneric("payNoticeLastTime"..info.subType, app.session:getServerTime())
		end
	end
end

-- 关闭付费弹窗界面
function ClassRef:closePayNoticeView()
	if not cc.isDead(self._payNoticeView) then
		self:removeChild(self._payNoticeView)
		self._payNoticeView = nil
		self._curPayNoticeId = nil
		EM:notify("onLoginedNoticeOver") -- 登录时候弹出的特权关闭的时候，需要发事件
	end
end

function ClassRef:updatePlayer(name, old, new)
	if name == "level" then
		local config = GD:queryActivityOpen()
		for i, v in ipairs(config) do
			if tonumber(v.openLv) > old and tonumber(v.openLv) <= new then -- 到达等级或者第一次跳级的时候都要弹
				if v.open_time and v.open_time ~= "" then
					-- 根据开启时间判断
					local flag = self._model:checkTimeOpen(v.open_time)
					if flag then
						self:openAdvert(v)
					end
				else
					local info = self._model:getWelfareActivityBySubType(tonumber(v.subType))
					if info then
						self:openAdvert(v)
					end
				end
			end
		end
	end
end

function ClassRef:openAdvert(data)
	if not data then return end
	local DesktopController = UIHandler:getDesktopController()
		if DesktopController then
			local desktop = DesktopController:getDesktop()
			if desktop then
				desktop:createAdvertNode(data)
			end
		end
end

------------------------------------------------------------
-- 神奇宝箱
-- 开启成功
function ClassRef:OpenAmazingAwardSuccess(data)
	if cc.isDead(self._view) then return end
	self._view:refreshAmazingAwardPanel(data, "succ")
end

-- 开启失败
function ClassRef:OpenAmazingAwardFail(data)
	if cc.isDead(self._view) then return end
	self._view:refreshAmazingAwardPanel(data, "fail")
end

function ClassRef:updateItem()
	if cc.isDead(self._view) then return end
	self._view:updateAmazingAwardMoney()
	--背包物品变动的时候也要刷新升级礼包界面
	self._view:updateThoughLvPanel()
end

function ClassRef:refreshAccumulatedRecharge()
	if cc.isDead(self._view) then return end
	if not self._curType or not self._curSubType then return end
	if self._curType == Enums.ActivityType.Welfare and self._curSubType == Enums.ActivitySubType.Give then
		self._model:reqGetTaskActivityData(self._curId)
	end
end

------------------------------------------------------------
--直升礼包
--掉落预览界面
function ClassRef:openLotteryDropView(data)
	if not data or #data == 0 then return end
	local view = LotteryDropView.new()
	view:onCloseView(function(sender)
		UIHandler:removePopupUiByKey(sender:getViewName())
	end)
	UIHandler:addPopupUi(view, view:getViewName())
	view:show()
	view:hideDes()
	view:performWithDelay(function()
		view:createList(data)
	end, 0)
end

function ClassRef:showQuickLvView(lv)
	UIHandler:getPopupUi():removeUIByKey(QuickLevelView:getViewName())

	local view = QuickLevelView.new()
	view:onCloseView(function(sender)
		UIHandler:removePopupUiByKey(sender:getViewName())
	end)

	view:refresh(string.format(L("levelpromotion6"), lv),nil)
	UIHandler:addPopupUi(view, view:getViewName())
	view:show()
end


--data{type,uid,price,iconPath,itemId}
--type == 1 为des
--type == 2 为购买界面需要另外4个参数
function ClassRef:showHeroTreasureBuyOrDes(data)
	if cc.isDead(self._heroTreasureBuyView) then
		self._heroTreasureBuyView = RewardHeroTreasureBuyView.new(app.mvc.VIEWTYPE_BLUR,data)
		self._heroTreasureBuyView:onCloseView(handler(self, self.closeHeroTreasureBuyView))
		self._heroTreasureBuyView:onClearView(handler(self, self.clearHeroTreasureBuyView))
		self._heroTreasureBuyView:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._heroTreasureBuyView)
	self._heroTreasureBuyView:show()
end

function ClassRef:closeHeroTreasureBuyView(data)
	if cc.isAlive(self._heroTreasureBuyView) then
		self:removeChild(self._heroTreasureBuyView, data)
	end
end

function ClassRef:clearHeroTreasureBuyView()
	if self._heroTreasureBuyView then
		self._heroTreasureBuyView = nil
	end
end

function ClassRef:closeHeroTreasureBuyViewAfterBuyGolden()
	if cc.isAlive(self._heroTreasureBuyView) then
		self._heroTreasureBuyView:closeView()
	end
end

--------------------购买黄金宝藏经验界面-----------------------
--data 为RewardHeroTreasureVo
function ClassRef:showHeroTreasureBuyExpView(data)
	if cc.isDead(self._heroTreasureBuyExpView) then
		self._heroTreasureBuyExpView = RewardHeroTreasureBuyExpView.new(app.mvc.VIEWTYPE_BLUR, data)
		self._heroTreasureBuyExpView:onCloseView(handler(self, self.closeHeroTreasureBuyExpView))
		self._heroTreasureBuyExpView:onClearView(handler(self, self.clearHeroTreasureBuyExpView))
		self._heroTreasureBuyExpView:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._heroTreasureBuyExpView)
	self._heroTreasureBuyExpView:show()
end

function ClassRef:closeHeroTreasureBuyExpView(data)
	if cc.isAlive(self._heroTreasureBuyExpView) then
		self:removeChild(self._heroTreasureBuyExpView, data)
	end
end

function ClassRef:clearHeroTreasureBuyExpView()
	if self._heroTreasureBuyExpView then
		self._heroTreasureBuyExpView = nil
	end
end

function ClassRef:closeHeroTreasureBuyExpAfterBuyExp()
	if cc.isAlive(self._heroTreasureBuyExpView) then
		self._heroTreasureBuyExpView:closeView()
	end
end

------------------显示黄金宝藏界面2个奖励合在一起的时候的tips---------------------
function ClassRef:showHeroTreasureTips(rewards, pos)
	if cc.isDead( self._heroTreasureTips ) then
		self._heroTreasureTips = RewardHeroTrearsureTipsPanel.create()

		self._view:addChild( self._heroTreasureTips )
		-- 点击空白区域关闭
		display.nodeRemoveForNotHit(self._heroTreasureTips, function()
			if cc.isAlive(self._heroTreasureTips) then
				self._heroTreasureTips:removeFromParent(true)
				self._heroTreasureTips = nil
			end
		end)
	end
	self._heroTreasureTips:setData(rewards)

	local width = self._heroTreasureTips:getContentSize2()
	local posX = pos.x
	if posX + width > display.width then
		posX = display.width - width
	end
	self._heroTreasureTips:setPosition( cc.p( posX, pos.y ) )
end

return ClassRef
